//
//  WebViewController.m
//  gdemm
//
//  Created by 乔明超 on 16/10/9.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "WebViewController.h"
#import "SVProgressHUD.h"
#import "UserDefaultsUtil.h"
#define DEVICEVERSION     [[[UIDevice currentDevice] systemVersion] floatValue]
@interface WebViewController ()<UIGestureRecognizerDelegate,WKNavigationDelegate,UIWebViewDelegate>
@property (strong, nonatomic) WKWebView *WKwebView;
@property (strong, nonatomic) UIWebView *webView;
@end

@implementation WebViewController
- (UIWebView *)webView{
    if (_webView == nil) {
        _webView = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:nil];
        
        longPress.delegate = self;
        
        longPress.minimumPressDuration = 0.4;
        
        [_webView addGestureRecognizer:longPress];
        [self.view addSubview:_webView];
    }
    return _webView;
}

- (WKWebView *)WKwebView{
    if (_WKwebView == nil) {
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc]init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        _WKwebView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:nil];
        _WKwebView.navigationDelegate = self;
        longPress.delegate = self; //记得在.h文件里加上委托
        longPress.minimumPressDuration = 0.4;
        
        [_WKwebView addGestureRecognizer:longPress];
        [self.view addSubview:_WKwebView];
    }
    return _WKwebView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    if ([DeviceTypeJudge isPadDeviceType]) {
        button.frame = CGRectMake(0, 0, 20, 20);
    }else{
        button.frame = CGRectMake(0, 0, 16, 16);
    }
    
    [button setImage:[[UIImage imageNamed:@"navigationBar_back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(leftButtonPopHandler) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;
    self.navigationItem.title = NSLocalizedString(@"str_cloud_disk",  @"云盘");

    // Do any additional setup after loading the view.
    //判断是否打开了水印策略，添加水印效果
    if ([[UserDefaultsUtil shareInstance] getBool:LC_OPENWATERMARKPOLICY]) {
        for (int i = 0; i < 3; i++) {
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, i * (WINDOWHEIGHT - 200)/2, 250, 80)];
            label.font = [UIFont systemFontOfSize:16];
            label.textColor = [UIColor grayColor];
            label.transform = CGAffineTransformMakeRotation(-M_1_PI);
            label.text =  [[UserDefaultsUtil shareInstance]getString:LC_WATRMARKTEXT];
              NSLog(@"DEVICEVERSION=%f",DEVICEVERSION);
            if (DEVICEVERSION <= 8.0) {
                [self.webView addSubview:label];
            }else{
               [self.WKwebView addSubview:label];
            }
           
        }
    }
    [self showFile];

}
-(void)leftButtonPopHandler{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}
- (void) showFile
{
    if (self.path)
    {
        HRLog(@"path = %@",self.path);
        NSFileManager * manager = [NSFileManager defaultManager];
        NSString * documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSError * error;
        NSString * tempPath =[NSString stringWithFormat:@"%@/tempPath",documentsPath] ;
       BOOL b = [manager createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:&error];
        NSString * filePath = [NSString string];
        NSArray * array = [self.path componentsSeparatedByString:@"."];
        NSString * typeStr = array[1];
        NSArray * fileNames = [self.path componentsSeparatedByString:@"&"];
        NSString * fileName = fileNames.lastObject;
         NSString * openUrl = [NSString string];
        if (b) {
            if ([typeStr isEqualToString:@"wpt"]||[typeStr isEqualToString:@"wps"]) {
                filePath  = [tempPath stringByAppendingString:[NSString stringWithFormat:@"/%@.doc",fileName]];
                if ([manager fileExistsAtPath:filePath]) {
                    openUrl = filePath;
                }else{
                    if ([manager copyItemAtPath:self.path toPath:filePath error:nil]){
                        openUrl = filePath;
                    }
                }
            }else if([typeStr isEqualToString:@"et"]||[typeStr isEqualToString:@"ett"]){
                filePath  = [tempPath stringByAppendingString:[NSString stringWithFormat:@"/%@.xls",fileName]];
                if ([manager fileExistsAtPath:filePath]) {
                    openUrl = filePath;
                }else{
                    if ([manager copyItemAtPath:self.path toPath:filePath error:nil]){
                        openUrl = filePath;
                    }
                }
               
            }else{
                openUrl = self.path;
            }
        }
        
        NSLog(@"oprn=%@",openUrl);
        NSURL* url = [NSURL fileURLWithPath:openUrl];
        if (url != nil)
        {
            if (DEVICEVERSION <= 8.0) {
              [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
            }else{
                [self.WKwebView loadFileURL:url allowingReadAccessToURL:url];
            }
            
        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

{
    return NO;
}

#pragma mark WKWebView的代理方法
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"str_pleaseWaitForTheFileLoaded...", @"请等待文件加载完成...")];
    
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
       [SVProgressHUD dismiss];
}
#pragma mark webView的代理方法

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:NSLocalizedString(@"str_pleaseWaitForTheFileLoaded...", @"请等待文件加载完成...")];
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    NSString * documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString * tempPath =[NSString stringWithFormat:@"%@/tempPath",documentsPath] ;
    [[NSFileManager defaultManager]removeItemAtPath:tempPath error:nil];
    
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
    NSError *errors;
    [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    if (DEVICEVERSION <= 8.0) {
        [[NSURLCache sharedURLCache] removeAllCachedResponses];//清除缓存  
    }else{
        [self removeWKWebViewCache];
        self.WKwebView.navigationDelegate = nil;
        [self.WKwebView removeFromSuperview];
    }
}
-(void)removeWKWebViewCache{
    NSSet *websiteDataTypes = [NSSet setWithArray:@[
                                                    WKWebsiteDataTypeDiskCache,
                                                    WKWebsiteDataTypeOfflineWebApplicationCache,
                                                    WKWebsiteDataTypeMemoryCache,
                                                    WKWebsiteDataTypeLocalStorage,
                                                    WKWebsiteDataTypeCookies,
                                                    WKWebsiteDataTypeSessionStorage,
                                                    WKWebsiteDataTypeIndexedDBDatabases,
                                                    WKWebsiteDataTypeWebSQLDatabases
                                                    ]];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes
                                               modifiedSince:dateFrom completionHandler:^{
                                                  
                                               }];
}


@end
